package com.tsinghua.discharge.common;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CORSFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //String []  allowDomain= {"http://218.199.33.75:9528","http://218.199.33.77:9528"};
        String origin = request.getHeader("origin");// 获取源站
        response.setHeader("Access-Control-Allow-Origin", origin);

        //Set allowedOrigins= new HashSet(Arrays.asList(allowDomain));
        //String originHeader=request.getHeader("Origin");
        //if(allowedOrigins.contains(originHeader)){


        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type,Access-Control-Allow-Origin, Accept");
        response.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域
       // response.setHeader("Access-Control-Allow-Credentials","true");
        filterChain.doFilter(servletRequest, servletResponse);
       // }

    }

    @Override
    public void destroy() {

    }

}
